/**
 * Notes: 知识库管理服务
 * Date: 2023-10-01 19:40:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');
const KnowledgeModel = require('../../model/knowledge_model.js');
const timeUtil = require('../../../../framework/utils/time_util.js');
const util = require('../../../../framework/utils/util.js');
const cloudUtil = require('../../../../framework/cloud/cloud_util.js');
const VectorService = require('../vector/vector_service.js');
const config = require('../../../../config/config.js');

class AdminKnowledgeService extends BaseProjectAdminService {

    /**
     * 构造函数
     */
    constructor() {
        super();
        this.vectorService = new VectorService();
    }

    /**
     * 添加知识库文档
     * @param {object} adminId 管理员ID
     * @param {object} formData 文档数据
     */
    async insertKnowledge(adminId, {
        title,
        content,
        desc = '',
        type = KnowledgeModel.TYPE.GENERAL,
        category = '',
        tags = '',
        sortOrder = 9999
    }) {
        this._checkAdminId(adminId);

        // 参数校验
        if (!title) throw new Error('标题不能为空');
        if (!content) throw new Error('内容不能为空');
        if (title.length > 100) throw new Error('标题不能超过100个字符');
        if (content.length > 20000) throw new Error('内容不能超过20000个字符');
        if (desc && desc.length > 200) throw new Error('描述不能超过200个字符');

        // 构建数据
        const data = {
            KNOWLEDGE_TITLE: title,
            KNOWLEDGE_CONTENT: content,
            KNOWLEDGE_DESC: desc,
            KNOWLEDGE_TYPE: type,
            KNOWLEDGE_CATEGORY: category,
            KNOWLEDGE_TAGS: tags,
            KNOWLEDGE_STATUS: KnowledgeModel.STATUS.SHOW,
            KNOWLEDGE_SORT: sortOrder,
            KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.PENDING,
            KNOWLEDGE_ADD_TIME: timeUtil.time(),
            KNOWLEDGE_EDIT_TIME: timeUtil.time(),
            KNOWLEDGE_ADD_IP: this._getIP(),
        };

        // 写入数据库
        const id = await KnowledgeModel.insert(data);
        
        // 添加到向量库
        if (id) {
            // 异步处理向量化，不需要等待完成
            this.vectorService.vectorizeDocument(id).catch(error => {
                console.error('向量化文档失败:', error);
            });
        }

        return {
            id
        };
    }

    /**
     * 更新知识库文档
     * @param {object} adminId 管理员ID
     * @param {string} id 知识库文档ID
     * @param {object} formData 文档数据
     */
    async editKnowledge(adminId, id, {
        title,
        content,
        desc,
        type,
        category,
        tags,
        sortOrder,
        status
    }) {
        this._checkAdminId(adminId);

        // 参数校验
        if (!id) throw new Error('未指定知识库文档ID');

        // 查询旧数据
        const old = await KnowledgeModel.getOne(id);
        if (!old) throw new Error('知识库文档不存在');

        // 构建更新数据
        const data = {};

        if (util.isDefined(title)) {
            if (!title) throw new Error('标题不能为空');
            if (title.length > 100) throw new Error('标题不能超过100个字符');
            data.KNOWLEDGE_TITLE = title;
        }

        if (util.isDefined(content)) {
            if (!content) throw new Error('内容不能为空');
            if (content.length > 20000) throw new Error('内容不能超过20000个字符');
            data.KNOWLEDGE_CONTENT = content;
        }

        if (util.isDefined(desc)) {
            if (desc && desc.length > 200) throw new Error('描述不能超过200个字符');
            data.KNOWLEDGE_DESC = desc;
        }

        if (util.isDefined(type)) {
            data.KNOWLEDGE_TYPE = type;
        }

        if (util.isDefined(category)) {
            data.KNOWLEDGE_CATEGORY = category;
        }

        if (util.isDefined(tags)) {
            data.KNOWLEDGE_TAGS = tags;
        }

        if (util.isDefined(sortOrder)) {
            data.KNOWLEDGE_SORT = sortOrder;
        }

        if (util.isDefined(status)) {
            data.KNOWLEDGE_STATUS = status;
        }

        // 判断是否需要重新向量化
        const needVectorize = (
            data.KNOWLEDGE_TITLE !== undefined ||
            data.KNOWLEDGE_CONTENT !== undefined
        );

        if (needVectorize) {
            data.KNOWLEDGE_VECTOR_STATUS = KnowledgeModel.VECTOR_STATUS.PENDING;
        }

        // 更新时间
        data.KNOWLEDGE_EDIT_TIME = timeUtil.time();
        data.KNOWLEDGE_EDIT_IP = this._getIP();

        // 更新数据
        await KnowledgeModel.edit(id, data);

        // 如果需要，重新向量化
        if (needVectorize) {
            // 异步处理向量化，不需要等待完成
            this.vectorService.vectorizeDocument(id).catch(error => {
                console.error('重新向量化文档失败:', error);
            });
        }

        return {
            id
        };
    }

    /**
     * 获取知识库文档详情
     * @param {string} id 知识库文档ID
     */
    async getKnowledgeDetail(id) {
        if (!id) throw new Error('未指定知识库文档ID');

        const knowledge = await KnowledgeModel.getOne(id);
        if (!knowledge) throw new Error('知识库文档不存在');

        return knowledge;
    }

    /**
     * 获取知识库文档列表
     * @param {object} adminId 管理员ID
     * @param {object} condition 查询条件
     * @param {object} options 选项
     * @param {object} options.search 搜索内容
     * @param {object} options.sortType 排序类型
     * @param {object} options.sortVal 排序值
     * @param {object} options.typeId 分类
     * @param {object} options.page 页码
     * @param {object} options.size 页大小
     * @param {object} options.isTotal 是否返回总页数
     * @param {object} options.oldTotal 上次总页数
     */
    async getKnowledgeList({
        search = '',
        sortType = '',
        sortVal = '',
        typeId = '',
        page = 1,
        size = 10,
        isTotal = true,
        oldTotal = 0
    }) {
        // 设置查询条件
        const where = {};

        // 搜索条件
        if (search) {
            where.or = [
                { KNOWLEDGE_TITLE: { $regex: search, $options: 'i' } },
                { KNOWLEDGE_CONTENT: { $regex: search, $options: 'i' } },
                { KNOWLEDGE_TAGS: { $regex: search, $options: 'i' } }
            ];
        }

        // 分类条件
        if (typeId) {
            if (typeId === 'vector_pending') {
                // 查询向量状态待处理
                where.KNOWLEDGE_VECTOR_STATUS = KnowledgeModel.VECTOR_STATUS.PENDING;
            } else if (typeId === 'vector_error') {
                // 查询向量状态失败
                where.KNOWLEDGE_VECTOR_STATUS = KnowledgeModel.VECTOR_STATUS.ERROR;
            } else if (typeId === 'vector_done') {
                // 查询向量状态已完成
                where.KNOWLEDGE_VECTOR_STATUS = KnowledgeModel.VECTOR_STATUS.VECTORIZED;
            } else {
                // 按文档类型查询
                where.KNOWLEDGE_TYPE = typeId;
            }
        }

        // 设置排序方式
        let orderBy = {
            KNOWLEDGE_SORT: 'asc',
            KNOWLEDGE_ADD_TIME: 'desc'
        };

        // 时间降序
        if (sortType && sortVal) {
            orderBy = {
                [sortType]: sortVal
            };
        }

        // 查询数据
        const result = await KnowledgeModel.getList(where, orderBy, page, size, isTotal, oldTotal);

        return result;
    }

    /**
     * 删除知识库文档
     * @param {object} adminId 管理员ID
     * @param {string} id 知识库文档ID
     */
    async delKnowledge(adminId, id) {
        this._checkAdminId(adminId);

        if (!id) throw new Error('未指定知识库文档ID');

        const knowledge = await KnowledgeModel.getOne(id);
        if (!knowledge) throw new Error('知识库文档不存在');

        // 软删除
        const data = {
            KNOWLEDGE_STATUS: KnowledgeModel.STATUS.HIDDEN,
            KNOWLEDGE_EDIT_TIME: timeUtil.time(),
            KNOWLEDGE_EDIT_IP: this._getIP()
        };

        await KnowledgeModel.edit(id, data);

        return {
            id
        };
    }

    /**
     * 批量重新向量化处理
     * @param {object} adminId 管理员ID
     * @param {number} limit 最大处理条数
     */
    async refreshVectors(adminId, limit = 100) {
        this._checkAdminId(adminId);

        // 查询需要处理的文档
        const documents = await KnowledgeModel.getAll({
            KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.PENDING,
            KNOWLEDGE_STATUS: KnowledgeModel.STATUS.SHOW
        }, '_id', limit);

        const total = documents.length;
        let success = 0;
        let fail = 0;

        // 按顺序处理
        for (const doc of documents) {
            try {
                const result = await this.vectorService.vectorizeDocument(doc._id);
                if (result) {
                    success++;
                } else {
                    fail++;
                    // 标记处理失败
                    await KnowledgeModel.edit(doc._id, {
                        KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.ERROR,
                        KNOWLEDGE_EDIT_TIME: timeUtil.time()
                    });
                }
            } catch (error) {
                console.error('向量化处理失败:', error);
                fail++;
                // 标记处理失败
                await KnowledgeModel.edit(doc._id, {
                    KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.ERROR,
                    KNOWLEDGE_EDIT_TIME: timeUtil.time()
                });
            }
        }

        return {
            total,
            success,
            fail
        };
    }
}

module.exports = AdminKnowledgeService; 